package com.xr.exception;

import com.xr.dto.ResultDto;
import com.xr.enums.ResultStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Arnold Yand
 * @summary 处理执行@RequestMapping之后（执行controller里的逻辑时）报出的异常
 * @time 2018/4/7 9:41
 */
@ControllerAdvice
@ResponseBody
public class GlobalBizExceptionHandler {

  private static Logger logger = LoggerFactory.getLogger(GlobalBizExceptionHandler.class);

  @ExceptionHandler(value=Exception.class)
  public ResultDto exceptionHandler(HttpServletRequest request, Exception exception) {
    logger.error("业务处理异常：", exception);
    ResultStatus resultStatus = ResultStatus.SYS_FAILED;
    ResultDto result = new ResultDto();
    result.setCode(resultStatus.getCode());
    result.setMessage(resultStatus.getMessage());

    // 约定系统中所有校验不通过都返回IllegalArgumentException
    if(exception instanceof BizException){
      result.setMessage(exception.getMessage());
    }

    if(logger.isDebugEnabled()){
      result.setData(exception.getMessage());
    }

    return result;
  }

}
